<?php
namespace app\ClubAdmin\controller;
use think\Db;
use think\Controller;
use think\Session;
class TrainersController extends Controller
{
    public function _initialize()
    {
        if (!Session::has('clubid')) {
            $this->redirect('index/index/index');
        }
    }

    public function index()
    {
        $trainers = db("trainers")
            ->order('tid asc')
            ->paginate(5);
        $this->assign('list', $trainers);
        return $this->fetch('trainers');

    }

    public function add()
    {
        $pic = request()->file('tpic');
        if ($pic) {

        }
        $info = $pic->rule('uniqid')->validate(['size' => 3000000, 'ext' => 'jpg,png,gif,jpeg'])->
        move(ROOT_PATH . 'public' . DS . 'static/img/trainers');
        if ($info == false) {
            $this->$pic->getError();
        }
        $data = [
            'tname' => input('tname'),
            'tpic' => $info->getSaveName(),
            'ttel' => input('ttel'),
            'tintro' => input('tintro'),
            'cid' => Session::get('clubid'),

        ];

        if (Db::name("trainers")->insert($data)) {
            $this->success('添加成功！');
        } else {
            $this->error('添加失败');
        }
    }

    public function delete()
    {
        $tid = input('id');
        if (db("trainers")->delete($tid)) {
            $this->success("删除成功");
        } else {
            $this->error("删除失败");
        }

    }

    public function edit()
    {
        $tid = input('id');
        $list = Db::name('trainers')->where('tid', $tid)->find();
        echo(json_encode($list));

    }

    public function show(){
        $tid=input('tid');
        $list=Db::name('trainers')->where('tid',$tid)->find();
        echo(json_encode($list)) ;

    }

    public function update()
    {
        $tid = input('tid');
        $pic = request()->file('tpic1');
        if ($pic) {
            $info = $pic->rule('uniqid')->validate(['size' => 3000000, 'ext' => 'jpg,png,gif,jpeg'])->
            move(ROOT_PATH . 'public' . DS . 'static/img/trainers');
            if ($info == false) {
                $this->$pic->getError();
            }
            $data = [
                'tname' => input('tname1'),
                'tpic' => $info->getSaveName(),
                'ttel' => input('ttel1'),
                'tintro' => input('tintro1'),


            ];

            if (Db::name('trainers')->where('tid', $tid)->update($data)) {
                $this->success('更新用户成功！');

            } else
                $this->error('更新用户失败');

        }
        else{
            $data = [
                'tname' => input('tname1'),
                'ttel' => input('ttel1'),
                'tintro' => input('tintro1'),


            ];

            if (Db::name('trainers')->where('tid', $tid)->update($data)) {
                $this->success('更新用户成功！');

            } else
                $this->error('更新用户失败');

        }
    }
}
